package leetcode; /**
 * description:
 * author:zt
 * date:2021-09-11
 */

import java.util.Arrays;

/**
 * 给定一个包括n 个整数的数组nums和 一个目标值target。找出nums中的三个整数，使得它们的和与target最接近。返回这三个数的和。假定每组输入只存在唯一答案。
 */
public class leetcode16 {
    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{-4, -1, 1, 2}, 1));
    }
    public static int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        int ans = Integer.MAX_VALUE;
        int res = 0;
        Arrays.sort(nums);
        for (int i = 0; i < len-2; i++) {
            if (nums[i]>target) break;
            if (i>0 && nums[i]==nums[i-1]) continue;
            int L = i+1;
            int R = len-1;
            while (L<R){
                int sum = nums[i]+nums[L]+nums[R];
                if (sum==0){
                    return 0;
                }
                else if (sum>target) {
                    if (sum-target<ans) {
                        ans = sum-target;
                        res = sum;
                    }
                    R--;
                }
                else if (sum<target) {
                    if (target-sum<ans) {
                        ans = target-sum;
                        res = sum;
                    }
                    L++;
                }
            }
        }
        return res;
    }
}
